package com.fm.webreader.html.table;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class HtmlTableReader {
	private static void doOneTd(HtmlTable<String> table, Element cell, int row) {
		if (!cell.attr("rowspan").isEmpty()) {
			int rowsCount = Integer.parseInt(cell.attr("rowspan"));
			if (!cell.attr("colspan").isEmpty()) {
				int colsCount = Integer.parseInt(cell.attr("colspan"));
				table.addRowElement(row, cell.text(), rowsCount, colsCount);
			} else {
				table.addRowElement(row, cell.text(), rowsCount, 1);
			}
		} else {
			if (!cell.attr("colspan").isEmpty()) {
				int colsCount = Integer.parseInt(cell.attr("colspan"));
				table.addRowElement(row, cell.text(), 1, colsCount);
			} else {
				table.addRowElement(row, cell.text());
			}
		}
	}

	public static HtmlTable<String> readTable(Element e) {
		HtmlTable<String> table = new HtmlTable<>();
		if (e.tagName().equals("table")) {
			Elements trs = e.select(">*>tr");
			int row = 0;
			for (Element tr : trs) {
				Elements ths_tds = tr.select(">td,th");
				if (ths_tds.isEmpty()) {
					if (table.getHeight() > row) {
						row++;
					}
					continue;
				}
				for (Element th_td : ths_tds) {
					doOneTd(table, th_td, row);
				}
				row++;
			}
			return table;
		} else {
			throw new RuntimeException("please give me a table!");
		}
	}
}
